import { state } from "./config.js";
import { currentRole, currentState } from "./index.js";
import { emit, scoket } from "./utils/scoket.js";

setTimeout(() => {
  state.roleName = localStorage.roleName || "我";
  const nameSpan = currentRole.querySelector(".name");
  if (nameSpan) {
    //玩家名称
    nameSpan.innerHTML = state.roleName;
    //玩家层级
    currentRole.style.zIndex = "1";
    currentState.role = localStorage.role;
  }
});
const p1 = document.querySelector(".p1Score") as HTMLDivElement;
const p2 = document.querySelector(".p2Score") as HTMLDivElement;
//有人加入游戏会发送当前状态
scoket.$on((res) => {
  if (res.path === "/start/init") {
    if (currentState.role === "p1") emit.all("p1", "/getState", state);
    if (currentState.role === "p2") emit.all("p2", "/getState", state);
  }
});
scoket.$on(({ path, role, value }) => {
  if (path !== "/getState") return;
  if (role === "p1") {
    p1.innerText = value.value.hp;
  }
  if (role === "p2") {
    p2.innerText = value.value.hp;
  }
});

setTimeout(() => {
  //初始化自己状态
  scoket.$emit({ role: currentState.role, path: "/start", value: state });
  if (currentState.role === "p1") {
    p1.innerText = state.hp + "";
  }
  if (currentState.role === "p2") {
    p2.innerText = state.hp + "";
  }
});
export const setScore = (str: "p1" | "p2", hp: number) => {
  if (str === "p1") {
    let p1Num = +p1.innerText;
    p1.innerText = p1Num + hp + "";
  }
  if (str === "p2") {
    let p1Num = +p1.innerText;
    p1.innerText = p1Num + hp + "";
  }
};
